<template>
	<view>
		<!-- 顶部导航 -->
		<view class="top-nav">
			<text class="jiantou" @click="navigateShop"></text>
			<text class="tab active">商品评价 ({{ reviews }})</text>
		</view>
		<!-- 评分概览 -->
		<view class="rating-summary">
			<text class="recommend" @click="navigateToShop">综合评分</text>
			<view class="left_review">
				<view class="average-score">
					<i class="score">{{ averageScore }}</i>
					<span style="font-size: 24rpx;">{{deep}}</span>
					<view class="start_deep">
						<u-rate :value="averageScore" active-color="#FA3534" inactive-color="#b2b2b2" size="19"
							allowHalf readonly gutter="1"></u-rate>
					</view>
				</view>
			</view>
			<image class="deep_img" src="../../static/img/deep.jpg" mode=""></image>
		</view>
		<!-- 评论列表 -->
		<scroll-view class="review-list">
			<view v-for="(review, index) in reviewCount" :key="index" class="review-item">
				<view class="review-header">
					<view class="review-content">
						<image :src="review.profilePrcture" class="avatar" />
						<text class="name">{{ review.username }}</text>
					</view>
					<view class="stars">
						<view class="zan_deep">
							{{getReviewText(review.rating)}}
						</view>
						<u-rate :value="review.rating" active-color="#FA3534" inactive-color="#b2b2b2" size="15"
							readonly gutter="1"></u-rate>
					</view>
				</view>
				<view class="comment">{{ review.reviewText }}
				</view>
				<view class="date">{{ formattedTime = formatTimeAgo(review.updatedAt) }} </view>
				<view class="huifu" @click="huifu(review)">
					<span>回复</span>
				</view>
				<view class="date address">{{ review.districtOrCounty }}</view>
				<u-popup :show="dialogVisible" overlayOpacity="0.1" mode="bottom" @close="dialogVisible = false"
					custom-class="custom-popup">
					<view class="popup-content">
						<u-input style="border-radius: 30rpx; background: #e3e3e3;" type="textarea"
							v-model="replyContent" :placeholder="huifuText" :height="200"></u-input>
						<view class="button-group">
							<span :class="{ 'show': replyContent.trim().length > 0}" @click="submitReply()">发布</span>
						</view>
					</view>
				</u-popup>
				<view class="zankai" @click="toggleExpand(review)"
					v-show="review.sonReviewsList && review.sonReviewsList.length > 0">
					<span style="color: #2367c7;">{{ review.isExpanded ? '收起回复' : selectContent }}</span>
				</view>
				<view v-show="review.isExpanded" v-for="(onreview, index) in review.sonReviewsList" :key="index"
					class="review-item review_son">
					<view class="review-header">
						<image :src="onreview.profilePrcture" class="avatar" />
						<text class="name sonName">{{ onreview.username }}</text>
					</view>
					<view class="comment">{{ onreview.reviewText }}</view>
					<view class="date">{{ formattedTime = formatTimeAgo(onreview.createdAt) }}</view>
					<view class="huifu" @click="huifu(onreview)">
						<span>回复</span>
					</view>
					<view class="date address">{{ onreview.districtOrCounty }}</view>
					<u-popup :show="dialogVisible" overlayOpacity="0.1" mode="bottom" @close="dialogVisible = false"
						custom-class="custom-popup">
						<view class="popup-content">
							<u-input type="textarea" v-model="replyContent" :placeholder="huifuText"
								:height="200"></u-input>
							<view class="button-group">
								<span :class="{ 'show': replyContent.trim().length > 0} "
									@click="submitReply()">发布</span>
							</view>
						</view>
					</u-popup>
				</view>
			</view>
		</scroll-view>
		<u-loadmore v-show="loadStatus" :status="status" icon="true" />
		<view class="bottom_box" v-show="this.displaybottom">
			{{bottom_box_content}}
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				status: 'loadmore',
				loadStatus: true,
				reviewCount: [],
				review: [],
				filledStar: '/static/star-filled.png',
				emptyStar: '/static/star-empty.png',
				reviews: null,
				averageScore: null,
				bottom_box_content: '',
				displaybottom: false,
				page: 1, //页数
				size: 8, //每页条数
				total: 0, //数据总条数
				deep: '',
				dialogVisible: false,
				replyContent: '',
				reviewId: null, // 用于存储当前回复的评价ID
				huifuText: '',
				selectContent: "展开更多回复",
				reviewsVo: {
					reviewId: 0,
					productId: null,
					userId: null,
					parentReviewId: null,
					rating: null,
					reviewText: null
				}
			};
		},
		onPullDownRefresh() {
			this.reviewCount = [];
			this.page = 1;
			this.fetchReviewsCount();
			this.fetchReviews();
			setTimeout(function() {
				uni.stopPullDownRefresh(); //停止页面加载动画
			}, 1000)
		},
		onReachBottom() {
			//页数加加
			this.page++,
				//再次回调查看评价内容
				this.fetchReviewsCount();
		},
		onLoad(e) {
			this.productId = e.productId;
			this.fetchReviewsCount();
			this.fetchReviews();
			console.log(this.averageScore);
			if (this.reviewCount.sonReviewsList !== null) {
				this.iszankai = true;
			}
		},
		methods: {

			//切换他的一个状态
			toggleExpand(review) {
				review.isExpanded = !review.isExpanded;
			},
			// zankai(review, select) {
			// 	if (select === "展开更多回复") {
			// 		console.log(select);
			// 		this.iszankai = true;
			// 		this.selectContent = "收起回复"
			// 	} else {
			// 		console.log(review);
			// 		this.iszankai = false;
			// 		this.selectContent = "展开更多回复"
			// 	}
			// },
			getReviewText(rating) {
				switch (rating) {
					case 0:
						return '。。';
					case 1:
						return '差评';
					case 2:
						return '就这';
					case 3:
						return '一般';
					case 4:
						return '还行';
					case 5:
						return '超赞';
					default:
						return '无';
				}
			},
			huifu(review) {
				this.huifuText = "回复" + review.username
				//this.reviewId = reviewId;
				this.dialogVisible = true;
				this.review = review
			},
			async submitReply() {
				if (!this.replyContent.trim()) {
					uni.showToast({
						title: '回复内容不能为空',
						icon: 'none'
					});
					return;
				}
				this.reviewsVo.productId = this.review.productId;
				this.reviewsVo.userId = this.review.userId;
				this.reviewsVo.parentReviewId = this.review.reviewId;
				this.reviewsVo.reviewText = this.replyContent;
				await this.request("/productReviews/insertProductReviews", "post", this.reviewsVo)
					.then(res => {
						if (res.data.code == 200) {
							this.page = 1;
							this.fetchReviewsCount();
							this.fetchReviews();
							setTimeout(() => {
								this.$router.go(0)
							}, 10)
							this.dialogVisible = false;
							this.replyContent = '';
							uni.showToast({
								title: '回复成功',
								icon: 'success'
							});
						}
					}).catch(res => {
						uni.showToast({
							title: '回复失败',
							icon: 'none'
						});
					});
			},
			fetchReviewsCount() {
				this.productId;
				this.page;
				this.size;
				this.request(`/productReviews/getParentReviews?productId=${this.productId}&page=${this.page}
				&size=${this.size}`, "get")
					.then((res) => {
						if (res.data.code == 200) {
							//把新查到的集合添加到原来的集合里面
							this.reviewCount = this.reviewCount.concat(res.data.result.list.map(review => ({
								...review,
								isExpanded: false
							})));
							this.calculateAverageScore();
						} else {
							this.displaybottom = true;
							this.loadStatus = false;
							this.bottom_box_content = res.data.message;
						}
						//this.reviewCount = res.data.result.list;
					})
					.catch((err) => {
						console.error(err);
					});
			},
			//计算平均星级
			calculateAverageScore() {
				//全部星星数默认为 0 
				let totalRating = 0;
				//拿到这个评价的总长
				let totalReviews = this.reviewCount.length;
				//计算每个星星数量的和
				this.reviewCount.forEach(review => {
					totalRating += review.rating;
				});
				console.log(totalRating);
				console.log(totalReviews);
				console.log((totalRating / totalReviews).toFixed(1));
				//toFixed 保留一位小数 
				this.averageScore = totalReviews > 0 ? (totalRating / totalReviews).toFixed(1) : 0;
				if (this.averageScore > 4) {
					this.deep = '满意';
				} else if (this.averageScore > 3) {
					this.deep = '还行';
				} else if (this.averageScore > 2) {
					this.deep = '一般';
				} else if (this.averageScore > 1) {
					this.deep = '难评';
				} else if (this.averageScore > 0) {
					this.deep = '差评';
				}
			},
			//解析时间
			formatTimeAgo(timeString) {
				// 解析从后端获取的时间字符串
				const receivedTime = new Date(timeString);
				// 获取当前时间
				const currentTime = new Date();
				// 计算时间差（以毫秒为单位）
				const timeDiff = currentTime - receivedTime;
				// 将时间差转换为秒、分钟、小时和天
				const seconds = Math.floor(timeDiff / 1000);
				const minutes = Math.floor(seconds / 60);
				const hours = Math.floor(minutes / 60);
				const days = Math.floor(hours / 24);
				// 根据时间差返回不同的格式
				if (days > 0) {
					// 如果时间差超过7天，显示月-日格式
					if (days >= 7) {
						return receivedTime.toLocaleDateString('zh-CN', {
							month: '2-digit',
							day: '2-digit'
						});
					} else {
						// 如果时间差在7天以内，显示“几天前”格式
						return `${days}天前`;
					}
				} else if (hours > 0) {
					// 如果时间差在一天以内但超过2小时，显示“几小时前”格式
					return `${hours}小时前`;
				} else if (minutes > 0) {
					// 如果时间差在2小时以内但超过1分钟，显示“几分钟前”格式
					return `${minutes}分钟前`;
				} else {
					// 如果时间差在1分钟以内，显示“刚刚”或其他适当的内容
					return '刚刚';
				}
			},
			fetchReviews() {
				this.request("/productReviews/getParentReviewsCount", "get", {
						productId: this.productId
					}).then((res) => {
						if (res.data.message == "操作成功！") {
							this.reviews = res.data.result;
						}
					})
					.catch((err) => {
						console.error(err);
					});
			},
			navigateShop() {
				uni.navigateTo({
					url: `/pages/Productdetails/ProductDetails?productId=${this.productId}`
				});
			},
		}
	};
</script>

<style scoped>
	.review {
		/* background-color: aqua; */
		margin: 10px 60px;
	}

	.jiantou {
		margin-left: -250rpx;
	}

	.jiantou::before {
		font-family: "iconfont" !important;
		content: "\e64e";
		font-size: 50rpx;
		color: black;
	}

	.top-nav {
		display: flex;
		justify-content: space-around;
		padding: 10px 0;
		border-bottom: 1px solid #ddd;
	}

	.tab {
		font-size: 16px;
		color: #333;
	}

	.tab.active {
		font-weight: bold;
		color: #000;
		text-align: center;
		margin-left: -300rpx;
	}

	.rating-summary {
		display: flex;
		padding: 20px;
		margin: 0 auto;
		border-bottom: 1px solid #ddd;
		height: 180rpx;
		background-color: #fafafa;
		border-radius: 20rpx;
		width: 600rpx;
		margin-top: 30rpx;
	}

	.recommend {
		font-size: 24rpx;
		color: #b0b0b0;
		margin-bottom: 10px;
	}

	.average-score {
		display: flex;
		align-items: center;
		color: red;
	}

	.start_deep {
		margin-top: 110rpx;
		margin-left: -150rpx;
	}

	.score {
		font-size: 2em;
		color: red;
		margin-right: 10px;
		font-size: 50rpx;
	}

	.stars {
		display: flex;
		margin-left: 110rpx;
		margin-top: -50rpx;

	}

	.custom-popup {
		background: rgba(0, 0, 0, 0.5);
		opacity: 0.2;
		/* 设置背景颜色为黑色，并且透明度为50% */
	}

	.popup-content {
		padding: 16px;
	}

	.zankai {
		margin-left: 120rpx;
		margin-top: 40rpx;
	}

	.button-group {
		position: relative;
		margin-top: rpx;
		transition: margin-left 0.3s;
	}

	.button-group span {
		display: block;
		background-color: red;
		border-radius: 30rpx;
		width: 150rpx;
		height: 65rpx;
		line-height: 65rpx;
		text-align: center;
		margin-top: -68rpx;
		font-size: 40rpx;
		color: #fff;
		opacity: 0;
		transition: opacity 0.3s, right 0.3s;
		position: absolute;
		right: -150rpx;
		/* 初始位置 */
	}

	.button-group span.show {
		opacity: 1;
		right: 1px;
		/* 输入框右侧的距离 */
	}

	.zan_deep {
		font-size: 20rpx;
		color: red;
		width: 60rpx;
		height: 30rpx;
		text-align: center;
		background-color: #fdecf2;
		margin-top: 5rpx;
	}

	.star {
		width: 20px;
		height: 20px;
	}

	.review-list {
		padding: 0 20px;
	}

	.review-item {
		display: flex;
		/* border-bottom: 1px solid #ddd; */
		padding: 10px 0;
		flex-wrap: wrap;
		margin-bottom: 30rpx;
		flex-direction: column;
		align-items: flex-start;
		justify-content: flex-end;
	}

	.review-content {
		display: flex;
	}

	.review-header {
		display: flex;
		flex-direction: column;
	}

	.avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
	}

	.name {
		margin-left: 10px;
		color: #898989;
	}

	.comment {
		display: flex;
		justify-content: space-between;
		flex-direction: column;
		flex-wrap: wrap;
		width: 480rpx;
		margin-top: 10rpx;
		margin-left: 110rpx;
	}

	.review-image {
		width: 100%;
		height: auto;
	}

	.sonName {
		margin-top: -90rpx;
		margin-left: 110rpx;
	}

	.date {
		color: #999;
		font-size: 30rpx;
		margin-left: 120rpx;
		/* margin-top: 5rpx; */
	}

	.address {

		margin-left: 220rpx;
		margin-top: -40rpx;
		width: 100rpx;
	}

	.huifu {
		color: #999;
		font-size: 30rpx;
		margin-top: -40rpx;
		margin-left: 340rpx;
		width: 100rpx;
	}

	.bottom_box {
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
		font-size: 40rpx;
		color: #ddd;
		bottom: 0;
	}

	.review_son {
		margin-left: 50rpx;
		border-bottom: none;
	}

	.stat_deep {
		margin-left: -170rpx;
		margin-top: 100rpx;
	}

	.deep_img {
		width: 380rpx;
		height: 160rpx;
		margin-top: 7rpx;
		margin-left: 20rpx;
	}

	.left_review {
		margin-left: -100rpx;
	}
</style>